package chen.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadUtil {
	private String upDir;
	private long maxSize = -1;
	private boolean dayDir = false;
	public UploadUtil(String upDir){
		this.upDir = upDir.endsWith("/")?upDir:this.upDir+"/";
	}
	public UploadUtil(String upDir,long maxSize){
		this.upDir = upDir.endsWith("/")?upDir:this.upDir+"/";
		this.maxSize = maxSize;
	}
	public UploadUtil(String upDir,long maxSize,boolean dayDir){
		this.upDir = upDir.endsWith("/")?upDir:this.upDir+"/";
		this.maxSize = maxSize;
		this.dayDir = dayDir;
	}
	public Map<String,String> upload() throws Exception{
		HttpServletRequest request = ContextUtil.getContext().getHttpServletRequest();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(!isMultipart){
			return null;
		}
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		
		if(this.maxSize>0){
			upload.setSizeMax(this.maxSize);
		}
		if(this.dayDir){
			String day = new SimpleDateFormat("yyyyMMdd").format(new Date());
			this.upDir += day+"/";
	    	File file = new File(upDir);
	    	if (!file.exists()) {
	    	   file.mkdir();
	    	}
		}

		List<FileItem> items = upload.parseRequest(request);
		Iterator<FileItem> iter = items.iterator();
		Map<String,String> files = new HashMap<String,String>();
		while (iter.hasNext()) {
		    FileItem item = iter.next();
		    if (!item.isFormField()) {
		    	String srcName = item.getName();
		    	String randomName = UUID.randomUUID().toString()+srcName.substring(srcName.lastIndexOf("."));
	            File savedFile = new File(randomName);
	            item.write(savedFile);
	            files.put(item.getFieldName(), randomName);
		    }
		}
		return files;
	}
}